package com.hunantv.mglive.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.data.live.ChatData;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 喊话动画类，从右至左，背景颜色顺序切换
 * Created by QiuDa on 15/12/15.
 */
public class LiveMsgView {
    private static final int QUEUE_NUM = 500; // 队列长度
    private static final int ANIM_BASE_TIME = 3800; //动画播放时间
    private static final int ANIM_UNIT = 100; //增加文字增加时间单位
    private int mWidth;
    private int mCount;
    private int mDispalyWidth;
    private boolean mIsDefautBg;
    private Boolean mIsFull = false;
    private Context mContext;
    private ViewGroup mViewGroup;

    private LayoutInflater mInflater;

    private final List<ChatData> mChatList = new ArrayList<>();
    private final List<View> mMsgView = new ArrayList<>();
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            ChatData chatData = null;
            synchronized (mChatList) {
                if (mChatList.size() > 0) {
                    chatData = mChatList.get(0);
                    mChatList.remove(0);
                }
                if (chatData != null) {
                    showView(chatData);
                } else {
                    mIsFull = false;
                }
            }

        }
    };

    public LiveMsgView(Context context, int width, ViewGroup viewGroup) {
        this.mWidth = width;
        this.mContext = context;
        this.mViewGroup = viewGroup;
        this.mInflater = LayoutInflater.from(mContext);
    }


    public synchronized void displayView(ChatData chatData) {
        synchronized (mChatList) {
            if (mIsFull) {
                if (mChatList.size() < QUEUE_NUM) {
                    mChatList.add(chatData);
                }
            } else {
                showView(chatData);
            }
        }
    }

    private synchronized void showView(ChatData chatData) {
        mIsFull = true;
        mCount = mCount % 5;
        final View view;
        ViewHolder mViewHolder;
        synchronized (mMsgView) {
            if (mMsgView.size() > 0) {
                view = mMsgView.get(0);
                mMsgView.remove(0);
                mViewHolder = (ViewHolder) view.getTag();
            } else {
                view = mInflater.inflate(R.layout.live_msg_layout, null);
                mViewHolder = new ViewHolder();
                mViewHolder.mIvIcon = (ImageView) view.findViewById(R.id.iv_live_msg_icon);
                mViewHolder.mTvName = (TextView) view.findViewById(R.id.tv_live_msg_name);
                mViewHolder.mTvMsg = (TextView) view.findViewById(R.id.tv_live_msg_text);
                view.setTag(mViewHolder);
            }
        }
        if (((Activity) mContext).isFinishing()) {
            synchronized (mChatList) {
                mChatList.clear();
                return;
            }
        }
        mViewHolder.mTvName.setText(chatData.getNickname());
        mViewHolder.mTvMsg.setText(chatData.getTip());
        int length = !StringUtil.isNullorEmpty(chatData.getNickname()) ? chatData.getNickname().length() : 0;
        length = !StringUtil.isNullorEmpty(chatData.getTip()) && chatData.getTip().length() > length ? chatData.getTip().length() : length;
        if (length > 50) {
            length = 50;
        }
        int mAnimDuration = ANIM_BASE_TIME + ANIM_UNIT * length;
        Glide.with(mContext).load(chatData.getAvatar()).transform(new GlideRoundTransform(mContext, R.dimen.height_30dp)).error(R.drawable.default_icon).into(mViewHolder.mIvIcon);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        int viewWidth = view.getMeasuredWidth();
        int viewHeight = view.getMeasuredHeight();
        if (!mIsDefautBg) {
            view.setBackgroundDrawable(getDrawable(mCount));
        } else {
            view.setBackgroundResource(R.drawable.gift_msg_bg);
        }
        Animation mAnim = new TranslateAnimation(Animation.ABSOLUTE, mWidth, Animation.ABSOLUTE, -viewWidth, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
        mAnim.setDuration(mAnimDuration);
        mAnim.setInterpolator(new LinearInterpolator());
        mAnim.setFillAfter(true);
        mAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mViewGroup.removeView(view);
                synchronized (mMsgView) {
                    mMsgView.add(view);
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mViewGroup.addView(view);
        FrameLayout.LayoutParams ps = new FrameLayout.LayoutParams(viewWidth, viewHeight);
        view.setLayoutParams(ps);
        view.startAnimation(mAnim);
        mHandler.sendEmptyMessageDelayed(0, mAnimDuration - ANIM_BASE_TIME + 500);
        mCount++;
    }


    private Drawable getDrawable(int count) {
        Drawable drawable;
        switch (count % 5) {
            case 0:
                drawable = mContext.getResources().getDrawable(R.drawable.live_msg_bg_1);
                break;
            case 1:
                drawable = mContext.getResources().getDrawable(R.drawable.live_msg_bg_2);
                break;
            case 2:
                drawable = mContext.getResources().getDrawable(R.drawable.live_msg_bg_3);
                break;
            case 3:
                drawable = mContext.getResources().getDrawable(R.drawable.live_msg_bg_4);
                break;
            default:
                drawable = mContext.getResources().getDrawable(R.drawable.live_msg_bg_5);
        }
        return drawable;
    }

    public void onPause() {
        synchronized (mIsFull) {
            mIsFull = true;
            mViewGroup.removeAllViews();
        }
    }

    public void onResume() {
        synchronized (mIsFull) {
            mIsFull = false;
        }
    }


    public void changeScreenConfig() {
        if (mContext != null) {
            DisplayMetrics mts = mContext.getResources().getDisplayMetrics();
            mWidth = mts.widthPixels;
        }
    }

    public void colseAutoBg() {
        mIsDefautBg = true;
    }

    class ViewHolder {
        ImageView mIvIcon;
        TextView mTvName;
        TextView mTvMsg;
    }


}
